#!/usr/bin/env python

import config
from log import log

'''
Modules management
'''
class modules(object):
    def __init__(self, group):
        self.modules = []

        if not config.MODULES.has_key(group):
            return

        for v in config.MODULES[group]:
            if not v['disabled']:
                self.modules.append((v['id'],[v['name.default'], v['ref']]))
        self.modules.sort(lambda a,b :cmp(a[0], b[0]))

    def get(self):
        return self.modules
        
    def findNeighborRefsByName(self, name):
        if not self.modules:
            return (None, None)
        
        cur = 0
        for item in self.modules:
            if item[1][0].lower() == name.lower():
                break
            cur += 1

        if cur >= len(self.modules):
            return (None, None)
        elif cur == 0: 
            return (self.modules[0][1][1], self.modules[1][1][1])
        elif cur == len(self.modules) - 1:
            return (self.modules[cur-1][1][1], self.modules[0][1][1])
        
        return (self.modules[cur-1][1][1], self.modules[cur+1][1][1])


    def findRefByName(self, name):
        for item in self.modules:
            if item[1][0].lower() == name.lower():
                return item[1][1]
        return None

